import { MultipartFile } from '@fastify/multipart';
import { createWriteStream } from 'fs-extra';
import { extname } from 'path';
import { configure } from '../core/configure';
export function generateFileName(file: string) {
  const currentDate = new Date();
  const year = currentDate.getFullYear(); // 获取当前年份
  const month = currentDate.getMonth() + 1; // 获取当前月份（注意月份是从0开始的，所以需要加1）
  const day = currentDate.getDate(); // 获取当前日期
  const timestamp = Date.now(); // 生成时间戳
  const randomString = Math.random().toString(36).substring(2, 8); // 生成随机字符串
  const imageName = `image_${year}${month}${day}_${timestamp}_${randomString}${extname(
    file,
  )}`; // 根据日期、时间戳和随机字符串生成图片名称
  return imageName;
}

export function writeFile(file: MultipartFile, filePath: string) {
  return new Promise(async (resolve, reject) => {
    const writeStream = createWriteStream(filePath);
    const buffer = await file.toBuffer();
    writeStream.write(buffer);
    writeStream.end();
    writeStream.on('finish', () => {
      resolve(true);
    });
    writeStream.on('error', (error) => {
      reject(error);
    });
  });
}

export function uploadFileToCos(
  file: MultipartFile,
  fileName: string,
  dir: string,
) {
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  return new Promise(async (resolve, reject) => {
    const cos = configure.cos as any;
    const buffer = await file.toBuffer();
    cos.putObject(
      {
        Bucket: 'lljq-1301637875' /* 填入您自己的存储桶，必须字段 */,
        APPID: '1301637875' /* 填入您的 APPID，必须字段 */,
        Region: 'ap-nanjing' /* 存储桶所在地域，例如 ap-beijing，必须字段 */,
        Key:
          dir +
          '/' +
          fileName /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
        Body: buffer, // 上传文件对象
      },
      function (err, data) {
        if (err) {
          reject(err);
        } else {
          resolve(data.Location);
        }
      },
    );
  });
}
